package com.osgix.common.utils;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtilsBean;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.util.WebUtils;

import com.osgix.common.orm.ibatis.BaseQuery;
import com.osgix.common.orm.ibatis.PageRequest;
import org.apache.commons.lang.StringUtils;

public class PageRequestFactory {
	public static final int MAX_PAGE_SIZE = 1000;

	static BeanUtilsBean beanUtils = new BeanUtilsBean();
	static {
		//用于注册日期类型的转换
		String[] datePatterns = new String[] { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm:ss.SSS",
				"HH:mm:ss" };
		ConvertRegisterHelper.registerConverters(beanUtils.getConvertUtils(), datePatterns);

		System.out.println("PageRequestFactory.MAX_PAGE_SIZE=" + MAX_PAGE_SIZE);
	}

	public static PageRequest bindPageRequest(PageRequest pageRequest, HttpServletRequest request) {
		if (StringUtils.isEmpty(pageRequest.getSortColumns()))
			return bindPageRequest(pageRequest, request, pageRequest.getSortColumns());
		else
			return bindPageRequest(pageRequest, request, null);
	}

	public static PageRequest bindPageRequest(PageRequest pageRequest, HttpServletRequest request,
			String defaultSortColumns) {
		if (pageRequest.getPageSize() > 0)
			return bindPageRequest(pageRequest, request, defaultSortColumns, pageRequest.getPageSize());
		else
			return bindPageRequest(pageRequest, request, defaultSortColumns, BaseQuery.DEFAULT_PAGE_SIZE);
	}

	/**
	 * 绑定PageRequest的属性值
	 */
	public static PageRequest bindPageRequest(PageRequest pageRequest, HttpServletRequest request,
			String defaultSortColumns, int defaultPageSize) {
		try {
			Map params = WebUtils.getParametersStartingWith(request, "");
			beanUtils.copyProperties(pageRequest, params);
		} catch (IllegalAccessException e) {
			throw new IllegalArgumentException("beanUtils.copyProperties() error", e);
		} catch (InvocationTargetException e) {
			throw new IllegalArgumentException("beanUtils.copyProperties() error", e.getTargetException());
		}
		if (pageRequest.getPageNumber() == 0)
			pageRequest.setPageNumber(ServletRequestUtils.getIntParameter(request, "pageNumber", 1));
		if (pageRequest.getPageSize() == 0)
			pageRequest.setPageSize(ServletRequestUtils.getIntParameter(request, "pageSize", defaultPageSize));
		if (StringUtils.isEmpty(pageRequest.getSortColumns()))
			pageRequest.setSortColumns(ServletRequestUtils.getStringParameter(request, "sortColumns",
					defaultSortColumns));

		if (pageRequest.getPageSize() > MAX_PAGE_SIZE) {
			pageRequest.setPageSize(MAX_PAGE_SIZE);
		}
		return pageRequest;
	}

}